!function($) {

  'use strict';

  var console = window.console || { log: function () {} };


  	/*=================================================*/
  	/*         【构建图片上传裁剪模态框dom】               */
  	/*=================================================*/
  	function buildAvatarModal(option) {
        // 组件id 拼接后缀 保证唯一性
        let randomSuffix = (((1+Math.random())*0x10000)|0).toString(16).substring(1);
        option.id = option.id
            ? option.id + randomSuffix
            : randomSuffix;
        $("#"+option.id).remove();
    			
  	    var title = option.title || '图片上传';
  	    var fileLabel = option.fileLabel || '选择本地图片';
  	    var sumitBtnText = option.sumitBtnText || '上传';
  	    var imgInputName = option.imgInputName || 'img';
      
  	    return '<div class="container" id="'+option.id+'">' +
  	              '<!-- Cropping modal -->' +
  	              '<div class="modal fade avatar-modal" style="z-index: 9999999;" aria-hidden="true" aria-labelledby="avatar-modal-label" role="dialog" tabindex="-1">' +
  	                '<div class="modal-dialog modal-lg">' +
  	                  '<div class="modal-content">' +
  	                    '<form class="avatar-form" action="" enctype="multipart/form-data" method="post">' +
  	                      '<div class="modal-header">' +
  	                        '<h4 class="modal-title" id="avatar-modal-label" style="margin-top: 0">'+title+'</h4>' +
  	                        '<button class="close" data-dismiss="modal" type="button">×</button>' +
  	                      '</div>' +
  	                      '<div class="modal-body">' +
  	                        '<div class="avatar-body">' +
  	
  	                          '<!-- Upload image and data -->' +
  	                          '<div class="avatar-upload">' +
  	                            '<input class="avatar-src" name="avatar_src" type="hidden">' +
  	                            '<input class="avatar-data" name="avatar_data" type="hidden">' +
  	                            '<div class="form-group">' +
  		                          '<label for="avatarInput">'+fileLabel+'</label>' +
  		                          '<input type="file" class="form-control-file avatar-input" name="'+imgInputName+'">' +
  		                        '</div>' +
  	                            //'<label for="avatarInput">'+fileLabel+'</label>' +
  	                            //'<input class="avatar-input btn btn-link" id="avatarInput" name="avatar_file" type="file">' +
  	                          '</div>' +
  	
  	                          '<!-- Crop and preview -->' +
  	                          '<div class="row">' +
  	                            '<div class="col-lg-9">' +
  	                              '<div class="avatar-wrapper"></div>' +
  	                            '</div>' +
  	                            '<div class="col-lg-3">' +
  	                              '<div class="avatar-preview preview-lg"></div>' +
  	                              '<div class="avatar-preview preview-md"></div>' +
  	                              '<div class="avatar-preview preview-sm"></div>' +
  	                            '</div>' +
  	                          '</div>' +
  	
  	                          '<div class="row avatar-btns">' +
  	                            '<!-- <div class="col-md-9">' +
  	                              '<div class="btn-group">' +
  	                                '<button class="btn btn-primary" data-method="rotate" data-option="-90" type="button" title="Rotate -90 degrees">Rotate Left</button>' +
  	                                '<button class="btn btn-primary" data-method="rotate" data-option="-15" type="button">-15deg</button>' +
  	                                '<button class="btn btn-primary" data-method="rotate" data-option="-30" type="button">-30deg</button>' +
  	                                '<button class="btn btn-primary" data-method="rotate" data-option="-45" type="button">-45deg</button>' +
  	                              '</div>' +
  	                              '<div class="btn-group">' +
  	                                '<button class="btn btn-primary" data-method="rotate" data-option="90" type="button" title="Rotate 90 degrees">Rotate Right</button>' +
  	                                '<button class="btn btn-primary" data-method="rotate" data-option="15" type="button">15deg</button>' +
  	                                '<button class="btn btn-primary" data-method="rotate" data-option="30" type="button">30deg</button>' +
  	                                '<button class="btn btn-primary" data-method="rotate" data-option="45" type="button">45deg</button>' +
  	                              '</div>' +
  	                            '</div> -->' +
  	                            '<div class="col">' +
  	                              '<button class="btn btn-primary btn-block avatar-save" type="button">'+sumitBtnText+'</button>' +
  	                            '</div>' +
  	                          '</div>' +
  	                        '</div>' +
  	                      '</div>' +
  	                      '<!-- <div class="modal-footer">' +
  	                        '<button class="btn btn-default" data-dismiss="modal" type="button">Close</button>' +
  	                      '</div> -->' +
  	                    '</form>' +
  	                  '</div>' +
  	                '</div>' +
  	              '</div><!-- /.modal -->' +
  	
  	              '<!-- Loading state -->' +
  	              '<div class="loading" aria-label="Loading" role="img" tabindex="-1"></div>' +
  	            '</div>';
	  }
  



  // ============================================================
  //                       【构造对象】
  // ============================================================
  function CropAvatar() {
	    this.$container = null;
      this.option = null;
      this.$avatarView  = null;
      this.$avatar      = null;
      this.$avatarModal = null;
      this.$loading     = null;
      this.$avatarForm  = null;
      this.$avatarUpload = null;
      this.$avatarSrc   = null;
      this.$avatarData  = null;
      this.$avatarInput = null;
      this.$avatarSave  = null;
      this.$avatarBtns  = null;
      this.$avatarWrapper = null;
      this.$avatarPreview = null;
      this.support.datauri = null;
      
      // ============================================================
      //                       【监听器】
      // ============================================================
      this.addListener = function (option) {
        this.$avatarView.on('click', $.proxy(this.click, this));
        this.$avatarInput.on('change', $.proxy(this.change, this));
        //this.$avatarForm.on('submit', $.proxy(this.submit, this));
        this.$avatarSave.on('click', $.proxy(this.submit, this));
        this.$avatarBtns.on('click', $.proxy(this.rotate, this));
      };


      // ============================================================
      //                       【提交事件】
      // ============================================================
      this.submit = function () {

        if (this.option.submit) {
        	let formData = new FormData();
            let _this = this;
            this.$img.cropper('getCroppedCanvas').toBlob(function (blob) {
                let fileType = blob.type.split('/')[1];
                blob.lastModifiedDate = new Date();
                //blob.type = fileType;
                formData.append(_this.option.imgInputName, blob);
                _this.option.submit(formData, _this);
            })
          //this.option.submit(new FormData(this.$avatarForm[0]), this);
        } 
        return false;
      };
  }




  CropAvatar.prototype = {
    constructor: CropAvatar,

    support: {
      fileList: !!$('<input type="file">').prop('files'),
      blobURLs: !!window.URL && URL.createObjectURL,
      formData: !!window.FormData
    },


    // ============================================================
    //                       【初始化】
    // ============================================================
    init: function (option) {
      // 将模态框缓存到当前的body中 
      $("body").append(buildAvatarModal(option));
      
      // 初始化自身组件对象
      this.$container = $("#" + option.id);
      this.option = option;

      // 触发显示dom
      this.$avatarView  = $(this.option.trigger);
      // 图像dom
      this.$avatar      = this.$avatarView.find('img');
      // 模态框dom
      this.$avatarModal = this.$container.find('.avatar-modal');
      // loading dom
      this.$loading     = this.$container.find('.loading');
      // 表单dom
      this.$avatarForm  = this.$avatarModal.find('.avatar-form');
      // 内容包裹 dom
      this.$avatarUpload = this.$avatarForm.find('.avatar-upload');
      // 图片地址内容 dom
      this.$avatarSrc   = this.$avatarForm.find('.avatar-src');
      // 图像数据 dom
      this.$avatarData  = this.$avatarForm.find('.avatar-data');
      // 图像input输入框 dom
      this.$avatarInput = this.$avatarForm.find('.avatar-input');
      // 提交按钮 dom
      this.$avatarSave  = this.$avatarForm.find('.avatar-save');
      // 其他操作按钮组 dom
      this.$avatarBtns  = this.$avatarForm.find('.avatar-btns');
      this.$avatarWrapper = this.$avatarModal.find('.avatar-wrapper');
      // 预览图片裁剪效果组
      this.$avatarPreview = this.$avatarModal.find('.avatar-preview');

      this.support.datauri = this.support.fileList && this.support.blobURLs;

      if (!this.support.formData) {
        this.initIframe();
      }
      // 初始化模态框
      this.initModal();
      // 增加事件监听器
      this.addListener(option);
      return this;
    },



    // ============================================================
    //                       【模态框初始化】
    // ============================================================
    initModal: function () {
      this.$avatarModal.modal({
        show: false
      });
    },

    // ============================================================
    //                       【触发dom 点击事件 模态框展示】
    // ============================================================
    click: function () {
      this.$avatarModal.modal('show');
    },

    // ============================================================
    //                       【图片改变事件】
    // ============================================================
    change: function () {
      var files, file;

      if (this.support.datauri) {
        files = this.$avatarInput.prop('files');
        if (files.length > 0) {
          file = files[0];
          if (this.isImageFile(file)) {
            if (this.url) {
              URL.revokeObjectURL(this.url); // Revoke the old one
            }
            this.url = URL.createObjectURL(file);
            this.startCropper();
          } else {
            this.alert("不支持的图片格式");
          }
        }
      } else {
        this.alert("不支持多图片裁剪");
      }
    },
    // ============================================================
    //                       【判断是否合法图片文件格式】
    // ============================================================
    isImageFile: function (file) {
      if (file.type) {
        return /^image\/\w+$/.test(file.type);
      } else {
        return /\.(jpg|jpeg|png|gif)$/.test(file);
      }
    },
    

    // ============================================================
    //          【图片裁剪功能  开启 与 关闭】 和模态框的关闭
    // ============================================================
    startCropper: function () {
      var _this = this;

      if (this.active) {
        this.$img.cropper('replace', this.url);
      } else {
        this.$img = $('<img src="' + this.url + '">');
        this.$avatarWrapper.empty().html(this.$img);
        var __cropp = this.$img.cropper({
          aspectRatio: this.option.aspectRatio || null,
          preview: this.option.preview? this.option.preview : this.$avatarPreview.selector,
          strict: true,
          crop: function (data) {
            var json = [
                  '{"x":' + data.x,
                  '"y":' + data.y,
                  '"height":' + data.height,
                  '"width":' + data.width,
                  '"rotate":' + data.rotate + '}'
                ].join();
            _this.$avatarData.val(json);
          }
        });
        this.active = true;
      }
    },
    stopCropper: function () {
      if (this.active) {
        this.$img.cropper('destroy');
        this.$img.remove();
        this.active = false;
      }
    },
    cropDone: function () {
      this.$avatarForm.get(0).reset();
      this.$avatar.attr('src', this.url);
      this.stopCropper();
      this.$avatarModal.modal('hide');
    },


    // ============================================================
    //                       【加载动画的 开启 与 关闭】
    // ============================================================
    startLoading: function() {
      this.$loading.fadeIn();
    },
    stopLoading: function() {
      this.$loading.fadeOut();
    },


    rotate: function (e) {
      var data;

      if (this.active) {
        data = $(e.target).data();

        if (data.method) {
          this.$img.cropper(data.method, data.option);
        }
      }
    },
    

    // ============================================================
    //                       【错误提示】
    // ============================================================
    alert: function (msg) {
      var $alert = [
            '<div class="alert alert-danger avater-alert">',
              '<button type="button" class="close" data-dismiss="alert">&times;</button>',
              msg,
            '</div>'
          ].join('');

      this.$avatarUpload.after($alert);
    }
  };



  $.CropAvatar = new CropAvatar, $.CropAvatar.Constructor = CropAvatar;
  $.CropAvatarBuilder = function(option) {
	  var ca = new CropAvatar();
	  ca.init(option);
	  return ca;
  }
}(window.jQuery);
